<template>
  <div class="layout-col bs flex1">
    <div class="ww100 flex-bc plr12 ptb8 bs2">
      <div class="flex-sc">
        <div class="h30">
          <img class="hh100" src="@/assets/images/tibi-ico.png" />
        </div>
        <span class="f15 fw ml8">{{publicStore.form.name? publicStore.form.name : '在线监测'}} <span class="i8">{{publicStore.form.alarm_time? parseTime(publicStore.form.alarm_time) + '告警' : ''}}</span></span>
      </div>
      <div class="flex-ec flex1">
        <div class="flex-sc cursor fontStyle" @click="toPath('/new', {type: publicStore.form.type})">
          <img class="w20 mr5" src="@/assets/images/back.png" />
          <span class="f15">设备列表</span>
        </div>
      </div>
    </div>
    <div class="ww100 hh100 overlay p12 flex-ss warp">
      <charttitle />
      <div class="flex3 layout-row">
        <chartjf v-if="publicStore.form.type == 'xx'" />
        <chartpd3in1 v-else-if="publicStore.form.type == 'pd_3in1' || publicStore.form.type == 'PD_JC_CSB_CYG'" />
        <chartmain v-else />
      </div>
    </div>
    <!-- <chartDot /> -->
    <chartBar3d />
  </div>
</template>

<script lang="ts" setup>
import chartBar3d from "@/views/async/chart/bar3d";
// import chartDot from "@/views/async/chart/dot";
import charttitle from "@/views/async/chart/title";
import chartpd3in1 from "@/views/async/chart/echart/pd3in1";
import chartjf from "@/views/async/chart/echart/jf";
import chartmain from "@/views/async/chart/echart/main";
const route = useRoute();
const { proxy }: any = getCurrentInstance();
const publicStore = proxy.publicStore();
const state = reactive({
  ...publicStore.$state,
  templateValue: [],
  dw: '{m}-{d} {h}:{i}:{s}',
  data0: [],
  data1: [],
  data2: [],
  data3: [],
  data4: [],
  data5: [],
  data6: [],
});

const init = async() => {
  await nextTick
  await getAttr()
  await getInit()
}

const getAttr = async() => {
  let query1 = {"o": "o_sensor_cfg_property",	"p": [publicStore.form.id], "i": 0}
  let query2 = {"o": "o_sensor_template_measure_property",	"p": [publicStore.form.type]}
  let query3 = {"o":"o_sensor_template_cfg_property","p":[publicStore.form.type], "i":0}
  let params = {queryApi1: query1, queryApi2: query2, queryApi3: query3}
  let res = await publicStore.post(params)
  state.templateValue = proxy.isNull(res.queryApi3)? [] : res.queryApi3
  publicStore._public.cfg = setCfg(res.queryApi1)
  publicStore._public.mea = res.queryApi2
}

const setCfg = (cfg_sensor) => {
  let vcArr = []
  let dwArr = []
  let temp = {}
  cfg_sensor.forEach(vv => {
    temp[vv.code] = vv.value
    let exist = state.templateValue.find(a=>a.code == vv.code)
    if(exist){
      if(vv.code.indexOf('vc_') != -1) vcArr.push({name: exist.name, code: vv.value})
      if(vv.code.indexOf('dw_') != -1) dwArr.push(vv.value)
    }
  });
  vcArr.forEach((vv, ii) => {
    vv.dw = dwArr[ii]
  });
  temp['values'] = vcArr
  return temp
}

const getInit = async() => {
  if(proxy.isNull(publicStore._public.cfg)) return console.log('自定义报错-------------------------未定义cfg')
  let query = []
  if(publicStore.status == 0){
    let mea = publicStore._public.mea.map(item => item.code)
    let temp = [publicStore.form.id].concat(mea)
    publicStore._public.cfg.values.forEach(v =>  {
      temp.push(v.code + '_tc')
      temp.push(v.code)
    })
    let query = {"o": "o_r_sensor", p: temp}
    let params = {queryApi: query}
    let res = await publicStore.post(params)
    if(proxy.isNull(res)) return
    publicStore._public.cfg.values.forEach(v =>  {
      if(res[0][v.code + '_tc']){
        res[0].timestamp = res[0][v.code + '_tc']
      }
    })
    state.data = res[0]
  }else{
    let tempArr = []
    let temp = {}
    await Promise.all(publicStore._public.cfg.values.map(async (v, i)=> {
      let mea = publicStore._public.mea.find(a=>a.code == v.code)
      let value_type = mea && mea.value_type == 'int'? 'o_sensor_measure_int' : 'o_sensor_measure_float'
      let query = {"o": value_type, "p": [publicStore.form.id, v.code, publicStore.datetime[0], publicStore.datetime[1]], "i": 5}
      let params = {queryApi: query}
      let res = await publicStore.post(params)
      if(!proxy.isNull(res)) {
        temp['timestamp'] = res[0].timestamp
        temp[v.code] = res[0].value
      }
      tempArr.push({code: v.code, value: res})
    }))
    await getMeas(temp)
    state.data = temp
    state.list = tempArr
    getData()
  }
  publicStore.form = Object.assign(publicStore.form, state.data)
  console.log('state.data-----------', state.data)
}

const getMeas = async(val) => {
  if (proxy.isNull(val.timestamp)) return console.log('无---')
  let query = {"o": "o_sensor_measure_int", "p": [publicStore.form.id, 'isAlarm', val.timestamp], "i": 0, "s": 0, "n": 1}
  let params = {queryApi2:  query}
  let res = await publicStore.post(params)
  let isAlarm = proxy.isNull(res)? '' : res[0].value
  publicStore.form.isAlarm = isAlarm
}

watch(() => publicStore.status, async (val) => {
  state.data0 = []
  state.data1 = []
  state.data2 = []
  state.data1 = []
  state.data2 = []
},{ immediate: false, deep: true });

watch(() => publicStore.form.timestamp, async (val) => {
  await nextTick();
  // if(publicStore.status == 1) return
  if(proxy.isNull(val)) return
  if(proxy.isNull(state.data)) return
  getData()
},{ immediate: false, deep: true });

watch(() => publicStore.isTrue, async (val) => {
  if(proxy.isNull(publicStore.chartDot)) return
  publicStore.form.timestamp = publicStore.chartDot[2]
  publicStore.data.forEach(v => {
    let exist = v.find(a=>a[2] == publicStore.form.timestamp)
    if(exist) publicStore.form[exist[3]] = exist[1]
  })
  getMeas({timestamp: publicStore.chartDot[2]})
},{ immediate: false, deep: true });

const getData = async() => {
  getValueData()
  getChartData()
}

const getValueData = async() => {
  let data = []
  if(publicStore.status == 0){
    console.log('实时-----------')
    publicStore._public.cfg.values.forEach((v, i) => {
      let markValue = [proxy.parseTime(state.data.timestamp, state.dw), state.data[v.code], state.data.timestamp, v.code]
      state['data' + i].push(markValue)
      let temp = setData(state['data' + i])
      data.push(temp)
    })
  }else{
    console.log('历史-----------')
    publicStore._public.cfg.values.forEach((v, i) => {
      let list = proxy.find(state.list, ['code', v.code], 'value')
      let tempArr = []
      list.forEach(vv => {
        let markValue = [proxy.parseTime(vv.timestamp, state.dw), vv.value, vv.timestamp, v.code]
        tempArr.push(markValue)
      })
      data.push(tempArr)
    })
  }
  publicStore.data = data
}

const setData = (list) => {
  let data = []
  list.forEach(v => {
    if(data.length>=20){
      data.shift()
      data.push(v)
    }else{
      data.push(v)
    }
  })
  return data
}

const getChartData = async() => {
    let chart = []
    let cfg = publicStore._public.cfg
    if (proxy.isNull(cfg)) return console.log('自定义报错-------------------------未定义cfg')
    if(!cfg.hasOwnProperty("p") || !cfg.hasOwnProperty("m")) return console.log('自定义报错-----------------------未定义p m')
    let p, o
    if(publicStore.status == 0){
      p = [publicStore.form.id, cfg.p, cfg.m]
      if(publicStore.form.type == "PD_THREE_ONE" || publicStore.form.type == 'pd_3in1' || publicStore.form.type == 'PD_JC_CSB_CYG'){
        o = "oh_r_3in1_pd_smp_data"
        chart = ["prpd_pd","prps_pd","prpd_ddb", "prps_ddb"]
      }else{
        o = "oh_r_std_smp_data"
        chart = ["prpd", "prps"]
      }
    }else{
      p = [publicStore.form.id, state.data.timestamp, cfg.p, cfg.m]
      if(publicStore.form.type == "PD_THREE_ONE" || publicStore.form.type == 'pd_3in1' || publicStore.form.type == 'PD_JC_CSB_CYG'){
        o = "oh_3in1_pd_smp_data"
        chart = ["prpd_pd","prps_pd","prpd_ddb", "prps_ddb"]
      }else{
        o = "oh_std_smp_data"
        chart = ["prpd", "prps"]
      }
    }
    let query = {"o": o, "p": p.concat(chart), "i": -1}
    let params = {highApi: query}
    let res = await publicStore.post(params)
    chart.forEach(v => {
      publicStore._public[v] = proxy.isNull(res)? [] : res[0][v]
    });
    console.log('publicStore._public-------', publicStore._public)
}

defineExpose({
  init
})

</script>

<style scoped lang="scss">

</style>
